package com.block.common.annotate.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.block.common.annotate.CachePutHash;
import com.block.common.service.LogFactory;
import com.block.common.util.SpelUtil;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 删除指定的hashey
 * 
 * @date 2021/1/25 1:38 下午
 */
@Aspect
@Component
public class CachePutHashAspect {
    private Logger logger = LogFactory.getCommLog();

    RedisTemplate redisStrTemplate;

    @Autowired
    public void setRedisTemplate(RedisTemplate redisStrTemplate) {
        this.redisStrTemplate = redisStrTemplate;
    }

    /**
     * 缓存中设置hashkey
     *
     * @param pjp
     * @param cachePutHash
     * @return
     * @throws Throwable
     */
    @Around("@annotation(cachePutHash)")
    public Object doAround(ProceedingJoinPoint pjp, CachePutHash cachePutHash) throws Throwable {
        String key = cachePutHash.key();
        String keyName = cachePutHash.keyName();
        /**
         * hash key
         */
        String hashKey = SpelUtil.getParams(pjp, keyName);
        //spel解析失败
        boolean noCache = ((StrUtil.isEmpty(hashKey)) || (StrUtil.isNotEmpty(hashKey) && hashKey.contains("#")));
        if (noCache) {
            Object object = pjp.proceed();
            return object;
        }
        boolean result = redisStrTemplate.opsForHash().hasKey(key, hashKey);
        if (result) {
            return redisStrTemplate.opsForHash().get(key, hashKey);
        }
        Object object = pjp.proceed();
        if (ObjectUtil.isNotEmpty(object)) {
            logger.info("put hash key:{} hashKey:{},Object:{}", key, hashKey, object);
            redisStrTemplate.opsForHash().put(key, hashKey, object);
            if (cachePutHash.timeout() != 0) {
                redisStrTemplate.expire(key, cachePutHash.timeout(), TimeUnit.SECONDS);
            }
        }
        return object;
    }
}
